<template>
  <div class="sql-audit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>SQL审核</span>
          <div>
            <el-select 
              v-model="statusFilter" 
              placeholder="状态筛选"
              style="width: 150px; margin-right: 10px"
              @change="loadRequests"
            >
              <el-option label="全部" value="" />
              <el-option label="待审核" value="pending" />
              <el-option label="已批准" value="approved" />
              <el-option label="已拒绝" value="rejected" />
              <el-option label="已执行" value="executed" />
              <el-option label="执行失败" value="failed" />
            </el-select>
            <el-button @click="loadRequests" :loading="loading">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table :data="requests" border style="width: 100%">
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="requester.username" label="申请人" width="100" />
        <el-table-column prop="request_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getRequestTypeTag(row.request_type)">
              {{ getRequestTypeText(row.request_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="database_instance.name" label="数据库" width="150" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              size="small"
              @click="viewRequest(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="row.status === 'approved'"
              size="small"
              type="warning"
              @click="executeRequest(row)"
            >
              执行
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              size="small"
              type="success"
              @click="approveRequest(row)"
            >
              批准
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              size="small"
              type="danger"
              @click="rejectRequest(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="loadRequests"
        />
      </div>
    </el-card>

    <!-- 请求详情对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="currentRequest?.title"
      width="80%"
      destroy-on-close
    >
      <div v-if="currentRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请人">
            {{ currentRequest.requester?.username || currentRequest.requester_name || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="数据库">
            {{ currentRequest.database_instance?.name || currentRequest.database_instance_name || '未指定' }}
          </el-descriptions-item>
          <el-descriptions-item label="请求类型">
            <el-tag :type="getRequestTypeTag(currentRequest.request_type)">
              {{ getRequestTypeText(currentRequest.request_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTag(currentRequest.status)">
              {{ getStatusText(currentRequest.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDate(currentRequest.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentRequest.description }}
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <h4>SQL内容：</h4>
          <el-input
            :model-value="currentRequest.sql_content"
            type="textarea"
            :rows="10"
            readonly
            style="font-family: 'Courier New', monospace"
          />
        </div>

        <div v-if="currentRequest.status === 'pending'" style="margin-top: 20px">
          <h4>审核操作：</h4>
          <el-form :model="reviewForm" label-width="80px">
            <el-form-item label="审核意见">
              <el-input
                v-model="reviewForm.comment"
                type="textarea"
                :rows="3"
                placeholder="请输入审核意见..."
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="success" 
                @click="submitReview('approve')"
                :loading="reviewing"
              >
                批准
              </el-button>
              <el-button 
                type="danger" 
                @click="submitReview('reject')"
                :loading="reviewing"
              >
                拒绝
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { sqlAPI } from '../../api/sql'
import { sqlWorkOrderAPI } from '../../api/sqlWorkOrder'

const requests = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('')

const dialogVisible = ref(false)
const currentRequest = ref(null)
const reviewing = ref(false)
const reviewForm = reactive({
  comment: ''
})

const loadRequests = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }
    if (statusFilter.value) {
      params.status = statusFilter.value
    }

    // 使用新的工单API
    const response = await sqlWorkOrderAPI.getWorkOrders(params)
    requests.value = response.results || response
    total.value = response.count || 0
  } catch (error) {
    console.error('加载请求列表失败:', error)
    ElMessage.error('加载请求列表失败')
  } finally {
    loading.value = false
  }
}

const viewRequest = async (request) => {
  try {
    console.log('获取工单详情，ID:', request.id)
    // 获取完整的工单详情
    const response = await sqlWorkOrderAPI.getWorkOrder(request.id)
    console.log('工单详情响应:', response)
    currentRequest.value = response
    reviewForm.comment = ''
    dialogVisible.value = true
  } catch (error) {
    console.error('获取工单详情失败:', error)
    ElMessage.error('获取工单详情失败')
  }
}

const approveRequest = async (request) => {
  try {
    await ElMessageBox.confirm('确定要批准这个SQL请求吗？', '确认操作', {
      type: 'warning'
    })
    
    await sqlAPI.reviewSQLRequest(request.id, {
      action: 'approve',
      comment: '批准执行'
    })
    
    ElMessage.success('SQL请求已批准')
    loadRequests()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批准请求失败:', error)
      ElMessage.error('批准请求失败')
    }
  }
}

const rejectRequest = async (request) => {
  try {
    const { value: comment } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝请求', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'textarea'
    })

    await sqlAPI.reviewSQLRequest(request.id, {
      action: 'reject',
      comment: comment || '拒绝执行'
    })

    ElMessage.success('SQL请求已拒绝')
    loadRequests()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝请求失败:', error)
      ElMessage.error('拒绝请求失败')
    }
  }
}

const executeRequest = async (request) => {
  try {
    // 检查是否是危险SQL
    const dangerousKeywords = ['DROP', 'DELETE', 'TRUNCATE', 'ALTER', 'CREATE', 'GRANT', 'REVOKE']
    const sqlUpper = request.sql_content.toUpperCase().trim()
    const isDangerous = dangerousKeywords.some(keyword => sqlUpper.startsWith(keyword))

    let confirmMessage = `确定要执行工单"${request.title}"吗？\n\n数据库：${request.database_instance_name}\nSQL类型：${request.request_type_display}`

    if (isDangerous) {
      const dangerousKeyword = dangerousKeywords.find(keyword => sqlUpper.startsWith(keyword))
      confirmMessage += `\n\n⚠️ 警告：检测到危险SQL操作（${dangerousKeyword}），执行后无法撤销！`
    }

    await ElMessageBox.confirm(confirmMessage, '确认执行', {
      type: isDangerous ? 'error' : 'warning',
      confirmButtonText: '确认执行',
      cancelButtonText: '取消'
    })

    const requestData = isDangerous ? { confirm_dangerous: true } : {}
    await sqlWorkOrderAPI.executeWorkOrder(request.id, requestData)

    ElMessage.success('工单执行成功')
    loadRequests()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('执行工单失败:', error)
      ElMessage.error(error.response?.data?.error || '执行工单失败')
    }
  }
}

const submitReview = async (action) => {
  reviewing.value = true
  try {
    await sqlAPI.reviewSQLRequest(currentRequest.value.id, {
      action,
      comment: reviewForm.comment
    })
    
    ElMessage.success(`SQL请求已${action === 'approve' ? '批准' : '拒绝'}`)
    dialogVisible.value = false
    loadRequests()
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败')
  } finally {
    reviewing.value = false
  }
}

const getRequestTypeText = (type) => {
  const map = {
    query: '查询',
    dml: 'DML变更',
    ddl: 'DDL变更',
    other: '其他'
  }
  return map[type] || type
}

const getRequestTypeTag = (type) => {
  const map = {
    query: 'info',
    dml: 'warning',
    ddl: 'danger',
    other: ''
  }
  return map[type] || ''
}

const getStatusText = (status) => {
  const map = {
    pending: '待审核',
    approved: '已批准',
    rejected: '已拒绝',
    executed: '已执行',
    failed: '执行失败'
  }
  return map[status] || status
}

const getStatusTag = (status) => {
  const map = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    executed: 'success',
    failed: 'danger'
  }
  return map[status] || ''
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  loadRequests()
})
</script>

<style scoped>
.sql-audit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
}
</style>
